<?php
/**
* 提现
*/
class Withdraw_model extends CI_Model
{
	private $_table = 'withdraw';
	
	/**
	 * 提现记录
	 */
	public function findByUid($uid)
	{
		$this->db->select('id, amount, bank_id');
		$this->db->from($this->_table);
		$this->db->where('uid', $uid);
		return $this->db->get();
	}

	/**
	 * 添加
	 */
	public function insertWithdraw($postData, $bank)
	{
		$data = array(
				'uid' 		   => $postData['uid'],
				'user_name'    => $postData['user_name'],
				'amount' 	   => $postData['amount'],
				'amount_carry' => $postData['amount_carry'],
				'bank_id' 	   => $bank->bank_id,
				'bank_name'    => $bank->bank_name,
				'bank_card'    => $bank->bank_card,
				'cardholder'   => $bank->cardholder,
				'pin' 		   => $bank->pin,
				'mobile_phone' => $bank->mobile_phone,
				'is_from' 	   => 2,
				'status' 	   => 2,
				'state' 	   => 0,
				'created_at'   => date('Y-m-d H:i:s'),
				'pay_time'	   => date('Y-m-d H:i:s'),
				'updated_at'   => '0000-00-00 00:00:00',
			);
	    $this->db->insert($this->_table, $data);
		return $this->db->insert_id();
	}

	/**
	 * 查找每个用户的提现记录
	 */
	public function withdrawList($params, $count, $start)
	{
		$this->db->select('withdraw.withdraw_id, amount_carry, amount, withdraw.status, withdraw.state, withdraw.created_at, withdraw_audit.state AS audit_state');
		$this->db->from($this->_table);
		$this->db->join("(SELECT withdraw_audit.withdraw_id, withdraw_audit.describe, withdraw_audit.state FROM withdraw_audit GROUP BY withdraw_audit.withdraw_id ORDER BY `withdraw_audit`.`audit_id` DESC) AS withdraw_audit", 
			'withdraw.withdraw_id=withdraw_audit.withdraw_id', 'LEFT');
		$this->db->where('withdraw.uid', $params['uid']);
		$this->db->where('withdraw.status', 2);
		$this->db->order_by('withdraw.withdraw_id', 'DESC');
		$this->db->limit($start, $count);
		return $this->db->get();
	}

	/**
	 * 统计总数
	 */
	public function withdrawTotal($params)
	{
		$this->db->select('withdraw_id');
		$this->db->from($this->_table);
		$this->db->where('uid', $params['uid']);
		return $this->db->count_all_results();
	}

	/**
	 * 更新支付状态
	 */
	public function updatePaystatus($id, $uid)
	{
		$data = array(
				'status' => 2, //支付
				'pay_time' => date('Y-m-d H:i:s')
			);
		$this->db->where('withdraw_id', (int)$id);
		$this->db->where('uid', (int)$uid);
		return $this->db->update($this->_table, $data);
	}
}